﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using RN.ERP.Web.ModelService;
using Newtonsoft.Json;
using Fly.Common.Linq;
using RN.ERP.Web.Utilities;
using System.Configuration;
using System.Web.SessionState;
using RN.ERP.Web.BasicService;
using RN.ERP.BLL;
using RN.ERP.BLL.Material;

namespace RN.ERP.Web.Handlers
{
    /// <summary>
    /// MateClassHandler 的摘要说明
    /// </summary>
    public class MateClassHandler : BaseHandler
    {
        string corpName = string.Empty;
        string corpUserGuid = string.Empty;
        string isrtUserGuid = string.Empty;
        string type = string.Empty;
        string appid = ConfigurationManager.AppSettings["AppId"];

        public override void ProcessRequest(HttpContext context)
        {
            corpName = context.Request.QueryString["corpName"];
            corpUserGuid = context.Request.QueryString["corpUserGuid"];
            isrtUserGuid = context.Request["IsrtUserGuid"];
            type = context.Request["type"];

            string corpInfo = context.Request["CorpInfo"];
            string sysInfo = context.Request["SysInfo"];

            string action = context.Request.QueryString["act"];
            if (!string.IsNullOrEmpty(action))
            {
                switch (action.ToLower())
                {
                    //case "getroles":
                    //    UtilitiesTool.OutputData(GetRoles(context), string.Empty);
                    //    break;
                    //case "getperusers":
                    //    UtilitiesTool.OutputData(GetPerUsers(context), string.Empty);
                    //    break;
                    case "getfunc":
                        UtilitiesTool.OutputData(GetFuncs(context), string.Empty);
                        break;
                    //case "getfuncforuser":
                    //    UtilitiesTool.OutputData(GetFuncsForUser(context), string.Empty);
                    //    break;
                    //case "getusers":
                    //    UtilitiesTool.OutputData(GetUsersInfo(context), string.Empty);
                    //    break;
                    //case "getsys":
                    //    UtilitiesTool.OutputData(GetSysApp(context, corpUserGuid), string.Empty);
                    //    break;
                    //case "dosaveuser":
                    //    UtilitiesTool.OutputData(SaveUserSys(context, corpInfo, sysInfo), string.Empty);
                    //    break;
                    //case "dosaverolebyre":
                    //    UtilitiesTool.OutputData(SaveRoleByRe(context), string.Empty);
                    //    break;
                    //case "getcainfo":
                    //    UtilitiesTool.OutputData(GetCAInfo(context, corpUserGuid), string.Empty);
                    //    break;
                    //case "saveper":
                    //    UtilitiesTool.OutputData(SavePermission(context), string.Empty);
                    //    break;
                    //case "addrole":
                    //    UtilitiesTool.OutputData(AddOrEditRole(context), string.Empty);
                    //    break;
                    //case "addmapping":
                    //    UtilitiesTool.OutputData(AddMapping(context), string.Empty);
                    //    break;
                    //case "deleterole":
                    //    UtilitiesTool.OutputData(DeleteRole(context), string.Empty);
                    //    break;
                    case "getmenu":
                        UtilitiesTool.OutputData(GetMenu(context), string.Empty);
                        break;
                    case "addfunc":
                        UtilitiesTool.OutputData(AddOrEditFunc(context), string.Empty);
                        break;
                    case "deletefunc":
                        UtilitiesTool.OutputData(DeleteFunc(context), string.Empty);
                        break;
                    //case "getdepartment":
                    //    UtilitiesTool.OutputData(GetDepartment(context), string.Empty);
                    //    break;
                    //case "adddepartment":
                    //    UtilitiesTool.OutputData(AddDepartment(context), string.Empty);
                    //    break;
                    //case "deletedepartment":
                    //    UtilitiesTool.OutputData(DeleteDepartment(context), string.Empty);
                    //    break;
                    default:
                        break;
                }
            }

        }


        private string DeleteFunc(HttpContext context)
        {
            string funcid = context.Request.QueryString["funcid"];
            MaterialClassBLL mc = new MaterialClassBLL();
            if (!string.IsNullOrEmpty(funcid))
            {
                RN.ERP.DTO.OperationResult result = mc.DeleteMaterialClass(funcid);
                return JsonConvert.SerializeObject(new { Message = result.Message });
            }
            return JsonConvert.SerializeObject(new { Message = "操作失败" });
        }


        private string AddOrEditFunc(HttpContext context)
        {
            SessionUserInfo user = (SessionUserInfo)HttpContext.Current.Session[SessionConstant.SESSION_USERINFO];
            string cMCName = context.Request.Params["cMCName"];
            MaterialBLL mb = new MaterialBLL();
            string cMemo = context.Request.Params["cMemo"];
            string iStatus = "0";
            string Id = context.Request.Params["FunctionGuid"];
            string cPMCCode = context.Request.Params["ParenGuid"] == null ? "0" : context.Request.Params["ParenGuid"];
            string cCUid = user.CorpUserGuid;
            string cUUid = user.CorpUserGuid;
            string dCDate = DateTime.Now.ToString();
            string dUDate = DateTime.Now.ToString();

            Guid pguid = Guid.Empty;
            Guid.TryParse(cPMCCode, out pguid);
            if (!string.IsNullOrEmpty(cMCName))
            {
                if (!string.IsNullOrEmpty(Id))//修改
                {
                    DTO.MateClass m = new DTO.MateClass();
                   // m.cCUID = Guid.Parse(cCUid);
                   // m.cMCCode = context.Request.Params["cMCCode"];
                    m.cMCName = cMCName;
                    m.cMemo = cMemo;
                    m.cPMCCode = cPMCCode;
                    m.cUUID = Guid.Parse(cUUid);
                   // m.dCDate = DateTime.Parse(dCDate);
                    m.dUDate = DateTime.Parse(dUDate);
                    m.iStatus = iStatus;
                    m.id = int.Parse(Id);

                    MaterialClassBLL mc = new MaterialClassBLL();
                    RN.ERP.DTO.OperationResult result = mc.EditMateClass(m);
                    return JsonConvert.SerializeObject(new { Message = result.Message });
                }
                else
                {
                    DTO.MateClass m = new DTO.MateClass();
                    m.cCUID = Guid.Parse(cCUid);
                    m.cMCName = cMCName;
                    m.cMemo = cMemo;
                    m.cPMCCode = cPMCCode;
                    m.cUUID = Guid.Parse(cUUid);
                    m.dCDate = DateTime.Parse(dCDate);
                    m.dUDate = DateTime.Parse(dUDate);
                    m.iStatus = iStatus;

                    MaterialClassBLL mc = new MaterialClassBLL();
                    RN.ERP.DTO.OperationResult result = mc.AddMaterialClass(m);
                    return JsonConvert.SerializeObject(new { Message = result.Message });
                }
            }
            return JsonConvert.SerializeObject(new { Message = "操作失败" });
        }


        private string GetMenu(HttpContext context)
        {
            string id = context.Request.QueryString["id"];
            string main = context.Request.QueryString["main"];
            return CreateParFuncs(id,main);
        }

        private string CreateParFuncs(string id, string main)
        {
            var data = new Dictionary<string, object>();
            if (main != "1")
            {
                data = new Dictionary<string, object>()
                {
                    {"text","物资类别"},
                    {"icon","/images/category.gif"},
                    {"MenuNo","0"},
                    {"cMCCode","0"},
                    {"id","0"}
                };
            }
            var dicChildren = new List<Dictionary<string, object>>();
            MaterialClassBLL mcb = new MaterialClassBLL();
            List<DTO.MateClass> functions = mcb.GetList(id);
            foreach (DTO.MateClass function in functions)
            {
                var dic = new Dictionary<string, object>()
                {
                    {"text",function.cMCName+"("+function.cMCCode+")"},
                    {"icon","/images/application.png"},
                    {"MenuParentNo",null},
                    {"MenuNo",function.cMCCode},
                    {"cMCCode",function.cMCCode},
                    {"id",function.id}
                };
                dicChildren.Add(dic);
            }
            var json = string.Empty;
            if (main != "1")
            {
                data["children"] = dicChildren;
                json = "[" + JsonConvert.SerializeObject(data) + "]";
            }
            else
            {
                json = JsonConvert.SerializeObject(dicChildren);
            }
            return json;
        }

        private string GetFuncs(HttpContext context)
        {
            MaterialClassBLL m = new MaterialClassBLL();
            List<DTO.MateClass> lm = new List<DTO.MateClass>();
            if (!string.IsNullOrEmpty(context.Request.QueryString["parent"]))
            {
                string parendId = context.Request.QueryString["parent"];
                lm = m.GetList(parendId);
            }
            else
            {
                lm = m.GetList("0");
            }
            return CreateFuncs(lm);
        }


        private string CreateFuncs(List<DTO.MateClass> listM)
        {
            var data = new List<Dictionary<string, object>>();
            foreach (DTO.MateClass function in listM)
            {
                var dic = ConvertFuncs(function);
                MaterialClassBLL mcb = new MaterialClassBLL();
                List<DTO.MateClass> function2 = mcb.GetList(function.cPMCCode);
               // var function2 = listM.Where(f => f.cPMCCode == function.cMCCode).ToList();
                if (function2 != null && function2.Count > 0)
                {

                    var dicChildren = new List<Dictionary<string, object>>();
                    foreach (DTO.MateClass functionSub in function2)
                    {
                        var dicSubMenu = ConvertFuncs(functionSub);

                        dicChildren.Add(dicSubMenu);
                    }
                    dic["children"] = dicChildren;
                }
                data.Add(dic);
            }
            return JsonConvert.SerializeObject(data);
        }


        private Dictionary<string, object> ConvertFuncs(DTO.MateClass entity)
        {
            return new Dictionary<string, object>()
            {
                {"Permit",false},
                {"cCUID",entity.cCUID},
                {"cMCCode",entity.cMCCode},
                {"cMCName",entity.cMCName}, 
                {"cMemo",entity.cMemo},
                {"cPMCCode",entity.cPMCCode},
                {"cUUID",entity.cUUID},
                {"dCDate",entity.dCDate},
                 {"cCUName",entity.cCUName},
                {"CUUName",entity.CUUName},
                {"dUDate",entity.dUDate},
                {"id",entity.id},
                {"iStatus",entity.iStatus}
            };
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}